package com.briup.controller;

import com.briup.bean.Employee;
import com.briup.service.EmployeeService;
import com.briup.util.Message;
import com.briup.util.MessageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wyq
 * @create 2021-09-22 21:06
 */
@Api(description = "员工接口管理")
@RestController
@Validated
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @ApiOperation("添加或更新员工")
    @PostMapping("saveOrUpdate")
    public Message saveOrUpdateEmployee(@Valid Employee employee, BindingResult result) {
        if (result.hasErrors()) {
            //校验失败，应该返回失败，在模态框中显示校验失败的错误信息
            Map<String, Object> map = new HashMap<>();
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError fieldError : errors) {
                System.out.println("错误的字段名：" + fieldError.getField());
                System.out.println("错误信息：" + fieldError.getDefaultMessage());
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return MessageUtil.error("数据格式不合法", map);
        } else if (employeeService.saveOrUpdate(employee) == 0) {
            return MessageUtil.error("操作失败");
        }
        return MessageUtil.success("操作成功");
    }

    @ApiOperation("删除员工信息")
    @DeleteMapping("delete")
    public Message deleteEmployee(@RequestParam @NotNull String id) {
        // 批量删除
        if (id.contains("-")) {
            ArrayList<Integer> list = new ArrayList<Integer>();
            String[] split = id.split("-");
            for (String s : split) {
                list.add(Integer.parseInt(s));
            }
            employeeService.deleteBatch(list);
            return MessageUtil.success("删除成功");
        } else if (employeeService.deleteById(Integer.parseInt(id)) > 0) {
            return MessageUtil.success("删除成功");
        }
        return MessageUtil.error("删除失败");
    }

    @ApiOperation("查询员工")
    @GetMapping("find")
    public Message queryEmployee(Integer id) {
        if (id != null) {
            Employee employee = employeeService.queryById(id);
            if (employee != null) {
                return MessageUtil.success("操作成功", employee);
            }
            return MessageUtil.error("该员工不存在");
        }
        List<Employee> employees = employeeService.queryAll();
        return MessageUtil.success("查询成功", employees);
    }

    @ApiOperation("查询员工数量")
    @GetMapping("queryCount")
    public Message queryEmployeeCount() {
        long count = employeeService.queryCount();
        return MessageUtil.success("查询成功", count);
    }

    @ApiOperation("检查用户名是否可用")
    @GetMapping("checkUser")
    public Message checkUser(String name) {
        //先判断用户名是否是合法的表达式;
        String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})";
        if (!name.matches(regx)) {
            return MessageUtil.error("用户名不合法");
        }
        List<Employee> employeeList = employeeService.queryByName(name);
        // 数据库用户名重复校验
        if (employeeList.size() != 0) {
            return MessageUtil.error("用户名已存在");
        }
        return MessageUtil.success("用户名可用");
    }

    @ApiOperation("分页查询")
    @GetMapping("query")
    public Message queryEmp(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber, @RequestParam(value =
            "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "navigatePages", defaultValue = "5") Integer navigatePages) {
        // 引入pageHelper 插件，
        PageHelper.startPage(pageNumber, pageSize);
        //startPage 后面紧跟的这个查询就是分页查询
        List<Employee> employeeList = employeeService.queryAll();
        // 使用pageInfo包装查询后的结果，只需要将pageInfo交给页面就行了。
        // 封装了详细的分页信息,包括有我们查询出来的数据，传入连续显示的页数
        PageInfo<Employee> pageInfo = new PageInfo<Employee>(employeeList, navigatePages);
        return MessageUtil.success("查询完毕", pageInfo);
    }
}
